<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 订单列表数据
const orderList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: [],
  orderType: ''
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 订单状态选项
const orderStatusOptions = [
  { label: '待付款', value: 'pending' },
  { label: '已付款', value: 'paid' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' },
  { label: '已退款', value: 'refunded' }
];

// 订单类型选项
const orderTypeOptions = [
  { label: '房间预订', value: 'room' },
  { label: '会员充值', value: 'recharge' },
  { label: '商品购买', value: 'goods' },
  { label: '团购券', value: 'voucher' }
];

// 支付方式选项
const paymentMethodOptions = [
  { label: '微信支付', value: 'wechat' },
  { label: '支付宝', value: 'alipay' },
  { label: '银行卡', value: 'card' },
  { label: '余额支付', value: 'balance' },
  { label: '现金', value: 'cash' }
];

// 加载订单数据
const loadOrderData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    orderList.value = Array.from({ length: 20 }, (_, index) => {
      const id = 'ORD' + (100000 + index).toString();
      const statusIndex = Math.floor(Math.random() * 5);
      const typeIndex = Math.floor(Math.random() * 4);
      const paymentIndex = Math.floor(Math.random() * 5);
      const now = new Date();
      const orderTime = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      
      // 随机金额
      const amount = Math.floor(Math.random() * 1000) + 50;
      
      // 随机会员信息
      const memberName = `会员${Math.floor(Math.random() * 100) + 1}`;
      const memberPhone = `1381234${(Math.floor(Math.random() * 10000)).toString().padStart(4, '0')}`;
      
      return {
        id,
        orderNo: id,
        memberName,
        memberPhone,
        amount: amount.toFixed(2),
        orderType: orderTypeOptions[typeIndex].value,
        orderTypeName: orderTypeOptions[typeIndex].label,
        status: orderStatusOptions[statusIndex].value,
        statusName: orderStatusOptions[statusIndex].label,
        paymentMethod: paymentMethodOptions[paymentIndex].value,
        paymentMethodName: paymentMethodOptions[paymentIndex].label,
        orderTime: orderTime.toLocaleString(),
        payTime: orderStatusOptions[statusIndex].value !== 'pending' 
          ? new Date(orderTime.getTime() + Math.floor(Math.random() * 60) * 60 * 1000).toLocaleString() 
          : '--',
        remark: Math.random() > 0.5 ? `备注信息${index + 1}` : ''
      };
    });
    
    pagination.total = 235; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadOrderData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadOrderData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadOrderData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  searchForm.orderType = '';
  
  pagination.currentPage = 1;
  loadOrderData();
};

// 查看订单详情
const viewOrderDetails = (row) => {
  ElMessage.info(`查看订单详情：${row.orderNo}`);
};

// 取消订单
const cancelOrder = (row) => {
  if (row.status !== 'pending') {
    ElMessage.warning('只能取消待支付的订单');
    return;
  }
  
  ElMessageBox.confirm(`确定要取消订单"${row.orderNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('取消成功');
    row.status = 'cancelled';
    row.statusName = '已取消';
  }).catch(() => {});
};

// 退款处理
const refundOrder = (row) => {
  if (row.status !== 'paid' && row.status !== 'completed') {
    ElMessage.warning('只能对已付款或已完成的订单进行退款');
    return;
  }
  
  ElMessageBox.confirm(`确定要退款订单"${row.orderNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('退款成功');
    row.status = 'refunded';
    row.statusName = '已退款';
  }).catch(() => {});
};

// 重新支付
const repayOrder = (row) => {
  if (row.status !== 'pending') {
    ElMessage.warning('只能对待支付的订单进行支付');
    return;
  }
  
  ElMessage.info(`跳转支付页面，订单号：${row.orderNo}`);
};

// 删除订单
const deleteOrder = (row) => {
  if (row.status !== 'cancelled' && row.status !== 'refunded') {
    ElMessage.warning('只能删除已取消或已退款的订单');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除订单"${row.orderNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功');
    loadOrderData();
  }).catch(() => {});
};

// 导出订单
const exportOrders = () => {
  ElMessage.success('订单数据导出成功');
};

// 初始化加载
onMounted(() => {
  loadOrderData();
});
</script>

<template>
  <div class="order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>订单管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="订单号/会员姓名/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in orderStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.orderType" placeholder="请选择" clearable>
            <el-option 
              v-for="item in orderTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div>
            <el-button type="success" @click="exportOrders">
              <el-icon><Download /></el-icon>
              导出订单
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="orderList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单号" width="120" />
        <el-table-column prop="memberName" label="会员姓名" width="100" />
        <el-table-column prop="memberPhone" label="手机号" width="120" />
        <el-table-column prop="orderTypeName" label="订单类型" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.orderType === 'room' ? 'success' : 
                row.orderType === 'recharge' ? 'primary' : 
                row.orderType === 'goods' ? 'warning' : 'info'
              "
            >
              {{ row.orderTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" width="100">
          <template #default="{ row }">
            ¥{{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethodName" label="支付方式" width="100" />
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'pending' ? 'warning' : 
                row.status === 'paid' ? 'primary' : 
                row.status === 'completed' ? 'success' : 
                row.status === 'cancelled' ? 'info' : 'danger'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="下单时间" width="160" />
        <el-table-column prop="payTime" label="支付时间" width="160" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewOrderDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              size="small" 
              type="primary" 
              @click="repayOrder(row)"
            >
              支付
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              size="small" 
              type="warning" 
              @click="cancelOrder(row)"
            >
              取消
            </el-button>
            <el-button 
              v-if="row.status === 'paid' || row.status === 'completed'"
              size="small" 
              type="danger" 
              @click="refundOrder(row)"
            >
              退款
            </el-button>
            <el-button 
              v-if="row.status === 'cancelled' || row.status === 'refunded'"
              size="small" 
              type="danger" 
              @click="deleteOrder(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.order-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 
